import re
from qturboframe.lib.webdriver.exceptions import SeleniumError
from BladeFerm.Lib.Common import logger
from BladeFerm.hui_app.hui_lib.tree import Tree as HuiTree


class Tree(HuiTree):
    '''
    对操作员中心有的菜单右侧的其他checkbox进行封装
    '''

    def select_by_node(self, node_name, opt_type):
        '''
        右侧带有勾选选项的多选树形控件选择

        :Args:
         - value: 树形结构顺序点击的节点值列表，例：[XX1/XX2/XX3, XX1/XX4/XX5]
         - opt_value: 对应节点要勾选的操作类型，例：[操作/授权, 操作]
        '''
        if isinstance(node_name, str):
            node_name = node_name.split(',')
        if isinstance(opt_type, str):
            opt_type = opt_type.split(',')
        for single_value in node_name:
            if single_value == '-':
                continue
            num = node_name.index(single_value)
            valuelist = single_value.split('/')
            # 打开树枝选项
            if len(valuelist) > 1:
                last_value = valuelist[-1]
                del valuelist[-1]
                temp_ul = self._element
                for va in valuelist:
                    if temp_ul is not None:
                        up_div = self.__open_node(temp_ul, va)
                        temp_ul = up_div
            else:
                temp_ul = self._element
                last_value = valuelist[0]
            # 选择树叶选项
            if temp_ul is not None:
                logger.info('选择树形节点：' + last_value)
                opt_valuelists = opt_type[num].split('/')
                span_text = temp_ul.find_element_by_attribute('xpath', './li/div/span[contains(@class,"h-tree-title")]/span[text()="{}"]'.format(last_value), timeout=self.timeout)
                for opt_valuelist in opt_valuelists:
                    span_opt = span_text.find_element_by_attribute('xpath', './following-sibling::div[@class="h-tree-check"]/label[contains(@class,"h-checkbox-wrapper")]', 'text:{0}'.format(opt_valuelist), timeout=self.timeout)
                    span_checkbox = span_opt.find_element_by_attribute('css selector', 'span.h-checkbox', timeout=self.timeout)
                    span_checkbox.secure_click()
                    logger.info('树形节点{0}: {1}勾选成功'.format(last_value, opt_valuelist))
            else:
                raise SeleniumError('中间节点未打开！')

    def node_checked(self, node_name, opt_type):
        '''
        右侧带有勾选选项的多选树形控件是否选中校验

        :Args:
         - value: 树形结构顺序点击的节点值列表，例：[XX1/XX2/XX3, XX1/XX4/XX5]
         - opt_value: 对应节点要勾选的操作类型，例：[操作/授权, 操作]
        '''
        if isinstance(node_name, str):
            node_name = node_name.split(',')
        if isinstance(opt_type, str):
            opt_type = opt_type.split(',')
        for single_value in node_name:
            if single_value == '-':
                continue
            num = node_name.index(single_value)
            valuelist = single_value.split('/')
            # 打开树枝选项
            if len(valuelist) > 1:
                last_value = valuelist[-1]
                del valuelist[-1]
                temp_ul = self._element
                for va in valuelist:
                    if temp_ul is not None:
                        up_div = self.__open_node(temp_ul, va)
                        temp_ul = up_div
            else:
                temp_ul = self._element
                last_value = valuelist[0]
            # 选择树叶选项
            if temp_ul is not None:
                logger.info('选择树形节点：' + last_value)
                opt_valuelists = opt_type[num].split('/')
                span_text = temp_ul.find_element_by_attribute('xpath', './li/div/span[contains(@class,"h-tree-title")]/span[text()="{}"]'.format(last_value), timeout=self.timeout)
                for opt_valuelist in opt_valuelists:
                    span_opt = span_text.find_element_by_attribute('xpath', './following-sibling::div[@class="h-tree-check"]/label[contains(@class,"h-checkbox-wrapper")]', 'text:{0}'.format(opt_valuelist), timeout=self.timeout)
                    span_checkbox = span_opt.find_element_by_attribute('css selector', 'span.h-checkbox', timeout=self.timeout)
                    if 'h-checkbox-checked' in span_checkbox.get_attribute('class'):
                        logger.info('树形节点{0}: {1}为勾选状态，校验通过'.format(last_value, opt_valuelist))
                    else:
                        raise SeleniumError('所选节点勾选校验未通过！')
            else:
                raise SeleniumError('中间节点未打开！')

    def __open_node(self, ul, node_name):
        re_open = 'h-tree-arrow-open'
        title_span = ul.find_element_by_attribute('xpath',
            './li/div/span[contains(@class,"h-tree-title")]/span[text()="{}"]'.format(node_name),
            timeout=self.timeout)
        arrow_span = title_span.find_element_by_attribute(
            'xpath', '../preceding-sibling::span[contains(@class,"h-tree-arrow")]', timeout=self.timeout)
        logger.debug("打开树形节点：" + node_name)
        if not re.search(re_open, arrow_span.get_attribute('class')):
            arrow_span.secure_click()
        next_ul = arrow_span.exist('xpath', './parent::div/following-sibling::ul', timeout=self.timeout)
        if next_ul:
            if not next_ul.is_displayed():
                next_ul = None
        return next_ul